package com.yingxin.yx.framework.security.handler;


import com.yingxin.yx.framework.jwt.TokenSupport;
import com.yingxin.yx.framework.security.user.PrincipalDto;
import com.yingxin.yx.framework.security.userdetails.OpenApiAccountUserDetailsService;
import com.yingxin.yx.framework.user.dto.TokenDto;
import com.yingxin.yx.framework.web.ResultUtil;
import com.yingxin.yx.framework.web.req.HttpHelper;
import com.yingxin.yx.framework.web.resp.RespHttp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @Description 返回token
 */
@Component
public class OpenApiAccountLoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private TokenSupport tokenSupport;

    @Autowired(required = false)
    private OpenApiAccountUserDetailsService openApiAccountUserDetailsService;

    /**
     * 登录成功返回结果
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        System.out.println("登录成功");
        PrincipalDto principal = (PrincipalDto) authentication.getPrincipal();
        principal.setIsApp("PC");
        WebAuthenticationDetails webAuthenticationDetails =
                ( WebAuthenticationDetails ) authentication.getDetails();
        principal.setLoginIP(webAuthenticationDetails.getRemoteAddress());
        principal.setLoginTime(new Date());
        TokenDto tokenDto = tokenSupport.getAccessToken(principal);
        tokenDto.setAvatar(principal.getAvatar());
        // 登录日志
        openApiAccountUserDetailsService.loginSuccessLog(principal, HttpHelper.getRequestInfo(request));
        ResultUtil.responseJson(request, response, RespHttp.ok(tokenDto));
    }

}